<?php

/**
 * This file is part of webman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */

use Webman\Route;
use app\common\Attribute;

/** @var  $dir_iterator *递归遍历目录查找控制器自动设置路由 */
// $dir_iterator = new \RecursiveDirectoryIterator(app_path());
$iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(app_path()));
/** @var  $suffix *读取config*/
$suffix = config('app.controller_suffix', '');
$suffix_length = strlen((string)$suffix);
// $arr = [];
foreach ($iterator as $file) {
    /** 忽略目录和非php文件 */
    if (is_dir($file) || $file->getExtension() != 'php') {
        continue;
    }

    $file_path = str_replace('\\', '/', $file->getPathname());
    /** 文件路径里不带controller的文件忽略 */
    if (!str_contains(strtolower($file_path), '/controller/')) {
        continue;
    }

    /**  只处理带 controller_suffix 后缀的 */
    if ($suffix_length && substr($file->getBaseName('.php'), -$suffix_length) !== $suffix) {
        continue;
    }

    // 根据文件路径是被类名
    /** @var  $class_name *根据文件路径获取类名 */
    $class_name = str_replace('/', '\\', substr(substr($file_path, strlen(base_path())), 0, -4));

    if (!class_exists((string)$class_name)) {
        echo "Class $class_name not found, skip route for it\n";
        continue;
    }
    $controller = new \ReflectionClass($class_name);
    foreach ($controller->getMethods(\ReflectionMethod::IS_PUBLIC) as $v) {

        /** 淘汰方法 */
        if (in_array($v->name, ['__construct', '__destruct'])) {
            continue;
        }

        $class = new \ReflectionMethod($v->class, $v->name);
        $attributes = $class->getAttributes(Attribute::class);

        // print_r($attributes);
        preg_match('/app(.*?)controller/', $v->class, $matches);
        $appName = str_replace('\\', "", $matches[1]); //应用名
        // echo $appName . "\n";
        $ClassShortName = str_replace(config('app.controller_suffix', ''), "", $controller->getShortName()); // 短class名不包括后缀
        $MethodShortName = $v->name; //方法名
        if (empty($attributes)) {
            continue;
        }
        foreach ($attributes as $attribute) {
            $data = $attribute->newInstance()->route();

            $firstChar = strtolower(substr($ClassShortName, 0, 1));
            $restOfString = substr($ClassShortName, 1);

            $name = "$appName.$firstChar$restOfString.$MethodShortName"; //命名

            $request = $data["request"];
            if (!$request) {
                $request = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];
            }
            $ClassShortName = strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $ClassShortName));
            $paths = [];
            $paths[] = "/$appName/$ClassShortName/$MethodShortName";
            $paths[] = "/$appName/$ClassShortName/$MethodShortName.html";
            if ($MethodShortName == "index") {
                $paths[] = "/$appName/$ClassShortName";
                $paths[] = "/$appName/$ClassShortName/";
                $paths[] = "/$appName/$ClassShortName.html";
                if ($ClassShortName == "index") {
                    $paths[] = "/$appName";
                    $paths[] = "/$appName" . "/";
                    $paths[] = "/$appName.html";
                    if ($appName == "index") {
                        $paths[] = "/";
                        $paths[] = "/$appName";
                        $paths[] = "/$appName.html";
                    }
                }
            }

            if ($data["middleware"]) {
                foreach ($paths as $path) {
                    Route::add($request, $path, [$v->class, $v->name])->name($name)->middleware($data["middleware"]);
                }
            } else {
                foreach ($paths as $path) {
                    Route::add($request, $path, [$v->class, $v->name])->name($name);
                }
            }
        }
    }
}

//关闭默认路由
Route::disableDefaultRoute();
